<?php

namespace App\Services;

use App\Models\Characteristic;
use App\Models\College;
use App\Models\CollegeCanKao;
use App\Models\CollegeCharacteristic;

class CollegeOtherDataUpdateSpiderService
{
    private $batchSize = 20; // 每次处理的院校数量

    /**
     * 主处理方法
     */
    public function crawlAllColleges()
    {
        echo "=== 开始处理院校标签等数据 ===\n";

        $page = 1;
        $collected = 0;
        while (true) {
            $colleges = College::query()
                ->skip(($page - 1) * $this->batchSize)
                ->take($this->batchSize)
                ->where('status', 0)
                ->orderBy('id', 'asc')
                ->get();

            if ($colleges->isEmpty()) {
                break;
            }

            foreach ($colleges as $college) {
                try {
                    echo "[处理] 开始处理院校ID: {$college->school_id} 院校名称: {$college->college_name}\n";
                    $bool = $this->crawlCollegeHandle($college);
                    if($bool) {
                        $college->markAsCrawled();
                        echo "[完成] 院校ID: {$college->school_id} 处理成功\n";
                    } else {
                        $college->recordError("处理失败");
                        echo "[错误] 院校ID: {$college->school_id} 处理失败: " . "\n";
                    }
                    $collected++;
                } catch (\Exception $e) {
                    echo "[错误] 院校ID: {$college->school_id} 处理失败: " . $e->getMessage() . "\n";
                    continue;
                }
            }
            $page++;
            echo "[等待] 批次处理完成，等待1秒...\n";
            sleep(1); // 批次间隔
        }
        echo "=== 处理完成 ===\n";
        echo "总共处理院校数: {$collected}\n";
    }

    public function crawlCollegeHandle(College $college): bool
    {
        return $this->handleCharacteristic($college);
    }

    public function handleCharacteristic(College $college): bool
    {
        $character = explode(" ", $college->characteristic);
        if ($character) {
            $ids = Characteristic::query()->whereIn('name', $character)->pluck('id')->toArray();
            if ($ids) {
                $data = [];
                foreach ($ids as $id) {
                    $data[] = [
                        'college_id' => $college->college_id,
                        'characteristic_id' => $id,
                        'create_time' => date('Y-m-d H:i:s')
                    ];
                }
                return CollegeCharacteristic::query()->insert($data);
            }
        }
        return true;
    }
}
